<?php

namespace app\api\controller;

use app\admin\model\dayrechargerecord\Dayrechargerecord;
use app\admin\model\fanfurecord\Fanfurecord;
use app\admin\model\hcbaorecord\Hcbaorecord;
use app\admin\model\identity\Identity;
use app\admin\model\jianshebaorecord\Jianshebaorecord;
use app\admin\model\level\Level;
use app\admin\model\news\News;
use app\admin\model\system\System;
use app\admin\model\teamrecord\Teamrecord;
use app\admin\model\wenjian\Wenjian;
use app\common\controller\Api;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;
use PHPMailer\PHPMailer\PHPMailer;
use think\Db;
use think\Exception;
use think\Session;


/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功222');
    }

    public function newslist(){
        $newsModel = new News();
        $list = collection($newsModel->where([])->field('id,title')->select())->toArray();
        $this->success('成功',$list);
    }

    public function newsdetail(){
        $id = $this->request->param('id');
        $newsModel = new News();
        $info = $newsModel->where(['id' => $id])->find()->toArray();
        $this->success('成功',$info);
    }

    /**每日静态收益**/
    public function onedayshouyi(){
        $userModel = new \app\admin\model\User();
        $dayrechargeModel = new Dayrechargerecord();
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();

        $where['send_day']=['<',365];
        $where['amount'] = ['>',0];
        // 获取所有状态为1的充值记录
        $list = collection($rechargeModel->where(['status'=>1,'is_over'=>0])->where($where)->select());

        if($list){
            $list = $list->toArray();
            Db::startTrans();
            try{
                // 现在$userAmounts是一个以user_id为键，总金额为值的数组
                foreach($list as $k => $v){
                    $userinfo = $userModel->where(['id'=>$v['user_id']])->find()->toArray();
                    if($userinfo['hc_balance']>0){
                        $usdt_amount = $rechargeModel->where(['status'=>1,'is_over'=>0,'user_id'=>$v['user_id'],'unit'=>2])->where($where)->sum('amount');
                        $hc_amount = $rechargeModel->where(['status'=>1,'is_over'=>0,'user_id'=>$v['user_id'],'unit'=>1])->where($where)->sum('amount');
                        $all_amount = $usdt_amount*$systeminfo['bili']+$hc_amount;
                        $one = $all_amount*3/365;
                        if($one>$userinfo['hc_balance']){
                            $one = $userinfo['hc_balance'];
                        }
                        //新增日收益
                        $indata['user_id'] = $v['user_id'];
                        $indata['chong_amount'] = $all_amount;
                        $indata['amount'] = $one;
                        $indata['create_time'] = time();
                        $indata['event'] = '用户'.$userinfo['nickname'].'充值日收益'.$one;
                        $dayrechargeModel->insert($indata);
                        //增加游客余额
                        $userModel->where(['id'=>$userinfo['id']])->update([
                            'shouyi_balance'=>$userinfo['shouyi_balance'] + $one,
                            'hc_balance'=>$userinfo['hc_balance'] - $one,
                            'jingtai_amount'=>$userinfo['jingtai_amount'] + $one,
                            'today_shouyi'=>$one
                        ]);

                        //修改充值信息
                        $rechargeModel->where(['id'=>$v['id']])->update([
                            'send_day'=>$v['send_day']+1,
                            'sheng_day'=>$v['sheng_day']-1,
                            'send_amount'=>$v['send_amount']+$one
                        ]);
                        $res= $rechargeModel->where(['id'=>$v['id']])->find()->toArray();
                        if($res['send_day']==365){
                            $rechargeModel->where(['id'=>$v['id']])->update([
                                'is_over'=>1,
                            ]);
                        }
                    }
                }
                Db::commit();
                $this->success('发放日收益成功');
            }catch(Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }


    /*public function test(){
        $mail = new PHPMailer(true);

        // 服务器配置 - 使用587端口
        $mail->isSMTP();
        $mail->Host = 'smtp.qq.com';
        $mail->SMTPAuth = true;
        $mail->Username = '309913834@qq.com';
        $mail->Password = 'gtmtppbcslrqbjeg';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 使用STARTTLS
        $mail->Port = 587; // 587端口

        // 编码设置
        $mail->CharSet = 'UTF-8';
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $arr=explode(",",$systeminfo['email']);
        if(count($arr)==1){
            // 发件人配置
            $mail->setFrom('309913834@qq.com', '合创城');
            $mail->addAddress($arr[0]);

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '测试邮件';
            $mail->Body = '测试是否有重复收到邮件或者收不到的情况';
            $mail->AltBody = "测试邮件";

            $mail->send();
        }else{
            foreach ($arr as $k=>$v){
                // 发件人配置
                $mail->setFrom('309913834@qq.com', '合创城');
                $mail->addAddress($v);

                // 邮件内容
                $mail->isHTML(true);
                $mail->Subject = '测试邮件';
                $mail->Body = '测试是否有重复收到邮件或者收不到的情况';
                $mail->AltBody = "测试邮件";

                $mail->send();
            }
        }
        $this->success('测试邮件发送成功');
    }*/

    public function test(){
        //$systemModel = new System();
        //$systeminfo = $systemModel->where(['id' => 1])->find()->toArray();
        $systeminfo['email']='309913834@qq.com';
        if (empty($systeminfo['email'])) {
            $this->error('没有配置邮箱地址');
        }

        $emailList = explode(",", $systeminfo['email']);
        $emailList = array_filter(array_map('trim', $emailList));

        if (empty($emailList)) {
            $this->error('邮箱地址列表为空');
        }

        // 初始化 PHPMailer
        $mail = new PHPMailer(true);

        // 服务器配置（只需设置一次）
        $mail->isSMTP();
        $mail->Host = 'smtp.qq.com';
        $mail->SMTPAuth = true;
        $mail->Username = '309913834@qq.com';
        $mail->Password = 'gtmtppbcslrqbjeg';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->CharSet = 'UTF-8';
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        $successCount = 0;
        $failCount = 0;
        $failEmails = [];

        foreach ($emailList as $email) {
            if (!$this->checkemail($email)) {
                $failCount++;
                $failEmails[] = $email . '(格式无效)';
                continue;
            }

            try {
                // 清理之前的收件人
                $mail->clearAddresses();
                $mail->clearCCs();
                $mail->clearBCCs();
                $mail->clearReplyTos();
                $mail->clearAllRecipients();
                $mail->clearAttachments();
                $mail->clearCustomHeaders();

                // 设置新的收件人
                $mail->setFrom('309913834@qq.com', '合创城');
                $mail->addAddress($email);

                // 邮件内容
                $mail->isHTML(true);
                $mail->Subject = '测试邮件';
                $mail->Body = '测试是否有重复收到邮件或者收不到的情况';
                $mail->AltBody = "测试邮件";

                if ($mail->send()) {
                    $successCount++;
                } else {
                    $failCount++;
                    $failEmails[] = $email;
                }
            } catch (Exception $e) {
                $failCount++;
                $failEmails[] = $email . '(' . $e->getMessage() . ')';
            }

            // 短暂延迟
            usleep(100000);
        }

        $message = "邮件发送完成：成功 {$successCount} 封，失败 {$failCount} 封";
        if (!empty($failEmails)) {
            $message .= "。失败邮箱：" . implode(', ', $failEmails);
        }

        $this->success($message);
    }

    public function checkemail($email){
        return filter_var(trim($email), FILTER_VALIDATE_EMAIL) !== false;
    }

    public function hcbao(){
        $userModel = new \app\admin\model\User();
        $hcbaoModel = new \app\admin\model\hcbao\Hcbao();
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $list = collection($hcbaoModel->where([])->select());
        if($list){
            $list = $list->toArray();
            Db::startTrans();
            try{
                foreach ($list as $k=>$v){
                    //查一下用户是否被删除
                    $userinfo = $userModel->where(['id'=>$v['user_id']])->find();
                    if($userinfo){
                        //写入累积收益
                        $one_shouyi = $v['amount']*$systeminfo['hc_bao']/100;
                        $one_shouyi = $one_shouyi/365;
                        $hcbaoModel->where(['user_id'=>$v['user_id']])->setInc('leiji_amount',$one_shouyi);
                        $hcbaoModel->where(['user_id'=>$v['user_id']])->setInc('send_amount',$one_shouyi);

                        //修改用户信息
                        $userModel->where(['id'=>$v['user_id']])->setInc('hcbao_amount',$one_shouyi);
                        $userModel->where(['id'=>$v['user_id']])->setInc('shouyi_balance',$one_shouyi);

                        $userinfo = $userModel->where(['id'=>$v['user_id']])->find()->toArray();

                        //写入一条HC宝发放纪录
                        $hcbaorecordModel = new Hcbaorecord();
                        $indata['user_id']=$v['user_id'];
                        $indata['all_amount'] = $v['amount'];
                        $indata['amount']=$one_shouyi;
                        $indata['event']='用户'.$userinfo['nickname'].'购买HC宝获取收益'.$one_shouyi;
                        $indata['create_time']=time();
                        $hcbaorecordModel->insert($indata);
                    }
                }
                Db::commit();
                $this->success('成功');
            }catch(Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            $this->success('没有符合条件的发放用户');
        }
    }

    public function yesterdayhcbao(){
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $hcbaoModel = new \app\admin\model\hcbao\Hcbao();
        $list = collection($hcbaoModel->where([])->select());
        if($list){
            $list = $list->toArray();

            foreach ($list as $k=>$v){
                //写入累积收益
                $one_shouyi = $v['amount']*$systeminfo['hc_bao']/100;
                $one_shouyi = $one_shouyi/365;
                $hcbaoModel->where(['user_id'=>$v['user_id']])->update(['yesterday_amount'=>$one_shouyi]);
            }
            $this->success('成功');
        }
    }

    public function fanfujiang(){
        $where['zhituinums']=['>=',8];
        $userModel = new \app\admin\model\User();
        $list = collection($userModel->where($where)->select());
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $fanfurecordModel = new Fanfurecord();
        if($list){
            $list = $list->toArray();
            Db::startTrans();
            try{
                foreach ($list as $k=>$v){
                    if($v['pid']>0){
                        //查下直推上家是否有充值
                        $pinfo = $userModel->where(['id'=>$v['pid']])->find();
                        if($pinfo){
                            $pinfo =$pinfo->toArray();
                            $shangjia_amount = $pinfo['hc_balance'];
                        }else{
                            $shangjia_amount=0;
                        }
                        //取出所有的直推用户
                        $userlist = collection($userModel->where(['pid'=>$v['id']])->select());
                        $idarr=[];
                        foreach ($userlist as $k1=>$v1){
                            array_push($idarr,$v1['id']);
                        }
                        $newarr=[];
                        //循环查询直推用户的充值是不是全大于100U
                        foreach ($idarr as $item){
                            $usdt_amount = $rechargeModel->where(['user_id'=>$item,'status'=>1,'unit'=>2])->sum('amount');
                            $hc_amount = $rechargeModel->where(['user_id'=>$item,'status'=>1,'unit'=>1])->sum('amount');
                            $amount = $usdt_amount+$hc_amount/$systeminfo['bili'];
                            if($amount>=100){
                                array_push($newarr,$item);
                            }
                        }
                        if(count($newarr)>=8 && $shangjia_amount>0){
                            $userinfo = $userModel->where(['id'=>$v['id']])->find()->toArray();
                            $pinfo = $userModel->where(['id'=>$v['pid']])->find()->toArray();

                            $shangjia_today_shouyi = $shangjia_amount/365;
                            $one_amount= $shangjia_today_shouyi*$systeminfo['fanfu_bili']/100;
                            if($one_amount>0){
                                $indata['from_user_id']=$pinfo['id'];
                                $indata['to_user_id']=$v['id'];
                                $indata['amount']=$one_amount;
                                $indata['event']='用户'.$pinfo['nickname'].'给用户'.$userinfo['nickname'].'反哺奖'.$one_amount;
                                $indata['bili']=$systeminfo['fanfu_bili'];
                                $indata['source_amount']=$shangjia_today_shouyi;
                                $indata['create_time'] = time();
                                $fanfurecordModel->insert($indata);
                                //修改用户余额
                                $userModel->where(['id'=>$v['id']])->setInc('fanfu_amount',$one_amount);
                                $userModel->where(['id'=>$v['id']])->setInc('shouyi_balance',$one_amount);
                            }
                        }
                    }
                }
                Db::commit();
                $this->success('发放反哺奖成功');
            }catch(Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    public function tepifanfujiang(){
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $userModel = new \app\admin\model\User();
        $fanfurecordModel = new Fanfurecord();
        if($systeminfo['fanfu_tepi_id']!=''){
            $arr=explode(",",$systeminfo['fanfu_tepi_id']);
            Db::startTrans();
            try{
                foreach ($arr as $k=>$v){
                    $userinfo = $userModel->where(['id'=>$v])->find()->toArray();
                    //取出上家静态收益
                    $pinfo = $userModel->where(['id'=>$v['pid']])->find();
                    if($pinfo){
                        $pinfo = $pinfo->toArray();
                        $shangjia_amount=$pinfo['hc_balance'];
                    }else{
                        $shangjia_amount=0;
                    }

                    //取出所有的直推用户
                    $userlist = collection($userModel->where(['pid'=>$v])->select());
                    if($userlist){
                        $userlist=$userlist->toArray();
                        $idarr=[];
                        foreach ($userlist as $item){
                            array_push($idarr,$item['id']);
                        }
                        $idstr=implode(",",$idarr);
                        $rwhere['user_id']=['in',$idstr];
                        //取出所有下家的总充值额
                        $all_usdt_amount = $rechargeModel->where($rwhere)->where(['status'=>1,'unit'=>2])->sum('amount');
                        $all_hc_amount = $rechargeModel->where($rwhere)->where(['status'=>1,'unit'=>1])->sum('amount');
                        $all_amount=$all_usdt_amount*$systeminfo['bili']+$all_hc_amount;
                        if($all_amount>0 && $shangjia_amount>0){
                            $pinfo = $userModel->where(['id'=>$userinfo['pid']])->find()->toArray();

                            $shangjia_today_shouyi = $shangjia_amount/365;
                            $one_amount= $shangjia_today_shouyi*$systeminfo['fanfu_bili']/100;
                            $indata['from_user_id']=$pinfo['id'];
                            $indata['to_user_id']=$v;
                            $indata['amount']=$one_amount;
                            $indata['event']='用户'.$pinfo['nickname'].'给用户'.$userinfo['nickname'].'反哺奖'.$one_amount;
                            $indata['bili']=$systeminfo['fanfu_bili'];
                            $indata['source_amount']=$shangjia_today_shouyi;
                            $indata['create_time'] = time();
                            $fanfurecordModel->insert($indata);
                            //修改用户余额
                            $userModel->where(['id'=>$v])->setInc('fanfu_amount',$one_amount);
                            $userModel->where(['id'=>$v])->setInc('shouyi_balance',$one_amount);
                        }
                    }
                }
                Db::commit();
                $this->success('特批反哺奖发送成功');
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            $this->success('特批反哺奖发送成功');
        }
    }

    public function testdayshouyi(){
        $userModel = new \app\admin\model\User();
        $dayrechargeModel = new Dayrechargerecord();
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();

        $where['send_day']=['lt',365];
        // 获取所有状态为1的充值记录
        $list = collection($rechargeModel->where(['status'=>1,'is_over'=>0,'user_id'=>279])->where($where)->select());

        if($list){
            $list = $list->toArray();
            Db::startTrans();
            try{
                // 现在$userAmounts是一个以user_id为键，总金额为值的数组
                foreach($list as $k => $v){
                    $userinfo = $userModel->where(['id'=>$v['user_id']])->find()->toArray();
                    $hc_amount = $v['amount']*$systeminfo['bili'];
                    //新增日收益
                    $indata['user_id'] = $v['user_id'];
                    $indata['chong_amount'] = $hc_amount;
                    $indata['amount'] = $hc_amount*3/365;
                    $indata['create_time'] = time();
                    $indata['event'] = '用户'.$userinfo['nickname'].'充值日收益';
                    $dayrechargeModel->insert($indata);
                    //增加游客余额
                    $userModel->where(['id'=>$userinfo['id']])->update([
                        'shouyi_balance'=>$userinfo['shouyi_balance'] + $hc_amount*3/365,
                        'hc_balance'=>$userinfo['hc_balance'] - $hc_amount*3/365,
                        'jingtai_amount'=>$userinfo['jingtai_amount'] + $hc_amount*3/365,
                        'today_shouyi'=>$hc_amount*3/365
                    ]);
                    //今日团队收益(先清零再算今日的)
                    //$teamwhere['id']=['IN',$userinfo['pids']];
                    //$userModel->where($teamwhere)->setInc('today_team_shouyi',$hc_amount*3/365);
                    //修改充值信息
                    $rechargeModel->where(['id'=>$v['id']])->update([
                        'send_day'=>$v['send_day']+1,
                        'sheng_day'=>$v['sheng_day']-1,
                        'send_amount'=>$v['send_amount']+$hc_amount*3/365
                    ]);
                    $res= $rechargeModel->where(['id'=>$v['id']])->find()->toArray();
                    if($res['send_day']==365){
                        $rechargeModel->where(['id'=>$v['id']])->update([
                            'is_over'=>1,
                        ]);
                    }
                }
                Db::commit();
                $this->success('发放日收益成功');
            }catch(Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    public function isupdate(){
        $this->success('成功',['is_update'=>1,'version'=>'1.0.15']);
    }

    public function shuoming(){
        $wenjianModel = new Wenjian();
        $info = $wenjianModel->where(['id'=>3])->find()->toArray();
        $this->success('成功',['content'=>$info['content']]);
    }


    /**申请提现**/
    public function withdrawsendcode(){
        $email = $this->request->param('email');
        if(!$email || $email==''){
            $this->error('邮箱必填');
        }

        // 验证单个邮箱格式
        if (!$this->checkemail($email)) {
            $this->error('邮箱格式无效');
        }

        try {
            // 初始化 PHPMailer
            $mail = new PHPMailer(true);

            // 服务器配置
            $mail->isSMTP();
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPAuth = true;
            $mail->Username = '3906570020@qq.com';
            $mail->Password = 'ynfxafymcczicejf';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->CharSet = 'UTF-8';
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            // 设置收件人
            $mail->setFrom('3906570020@qq.com', '合创城');
            $mail->addAddress($email);

            // 生成验证码
            $code = $this->getcode();
            Session::set('WITHDRAW_CODE', $code);

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '申请提现';
            $mail->Body = '您申请提现的验证码为：'.$code;
            $mail->AltBody = "申请提现";
            if ($mail->send()) {
                $this->success('验证码发送成功');
            } else {
                $this->error('邮件发送失败');
            }

        } catch (Exception $e) {
            $this->error('邮件发送失败：' . $e->getMessage());
        }
    }

    public function anquansendcode(){
        $email = $this->request->param('email');
        if(!$email || $email==''){
            $this->error('邮箱必填');
        }

        // 验证单个邮箱格式
        if (!$this->checkemail($email)) {
            $this->error('邮箱格式无效');
        }

        try {
            // 初始化 PHPMailer
            $mail = new PHPMailer(true);

            // 服务器配置
            $mail->isSMTP();
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPAuth = true;
            $mail->Username = '3906570020@qq.com';
            $mail->Password = 'ynfxafymcczicejf';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->CharSet = 'UTF-8';
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            // 设置收件人
            $mail->setFrom('3906570020@qq.com', '合创城');
            $mail->addAddress($email);

            // 生成验证码
            $code = $this->getcode();
            Session::set('ANQUAN_CODE', $code);

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '设置安全密码';
            $mail->Body = '您设置安全密码的验证码为：'.$code;
            $mail->AltBody = "设置安全密码";
            if ($mail->send()) {
                $this->success('验证码发送成功'.$code);
            } else {
                $this->error('邮件发送失败');
            }

        } catch (Exception $e) {
            $this->error('邮件发送失败：' . $e->getMessage());
        }
    }

    public function findsendcode(){
        $email = $this->request->param('email');
        if(!$email || $email==''){
            $this->error('邮箱必填');
        }

        // 验证单个邮箱格式
        if (!$this->checkemail($email)) {
            $this->error('邮箱格式无效');
        }

        try {
            // 初始化 PHPMailer
            $mail = new PHPMailer(true);

            // 服务器配置
            $mail->isSMTP();
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPAuth = true;
            $mail->Username = '3906570020@qq.com';
            $mail->Password = 'ynfxafymcczicejf';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->CharSet = 'UTF-8';
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            // 设置收件人
            $mail->setFrom('3906570020@qq.com', '合创城');
            $mail->addAddress($email);

            // 生成验证码
            $code = $this->getcode();
            Session::set('FIND_CODE', $code);

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '找回密码';
            $mail->Body = '您找回密码的验证码为：'.$code;
            $mail->AltBody = "找回密码";
            if ($mail->send()) {
                $this->success('验证码发送成功'.$code);
            } else {
                $this->error('邮件发送失败');
            }

        } catch (Exception $e) {
            $this->error('邮件发送失败：' . $e->getMessage());
        }
    }

    public function getcode(){
        $code='';
        for($i=0;$i<6;$i++){
            $code.=mt_rand(0,9);
        }
        return $code;
    }

    public function setwithcode(){
        $code = $this->getcode();
        Session::set('TEST',$code);
        $this->success('ok',['code'=>$code]);
    }

    public function getwithcode(){
        echo Session::get('WITHDRAW_CODE');
    }

    public function xiaozhengteamandlevel(){
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $userModel = new \app\admin\model\User();
        $levelModel = new Level();
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $one = $levelModel->where(['id'=>1])->find()->toArray();
        $two = $levelModel->where(['id'=>2])->find()->toArray();
        $three = $levelModel->where(['id'=>3])->find()->toArray();
        $four = $levelModel->where(['id'=>4])->find()->toArray();
        $five = $levelModel->where(['id'=>5])->find()->toArray();
        $six = $levelModel->where(['id'=>6])->find()->toArray();
        $list = collection($userModel->where([])->select());
        if($list){
            $list = $list->toArray();
            Db::startTrans();
            try{
                foreach ($list as $k=>$v){
                    $childlist = collection($userModel->where("FIND_IN_SET(?, pids)", [$v['id']])->select());
                    if($childlist){
                        $childlist = $childlist->toArray();
                        $idarr=[];
                        foreach ($childlist as $kk=>$vv){
                            array_push($idarr,$vv['id']);
                        }
                        $idstr=implode(",",$idarr);
                        $rwhere['user_id'] = ['in',$idstr];
                        $team_amount = $rechargeModel->where($rwhere)->where(['status'=>1])->sum('amount');
                        $team_amount = $team_amount*$systeminfo['bili'];
                        $userModel->where(['id'=>$v['id']])->update(['team_amount'=>$team_amount]);
                        //修正等级
                        if($v['is_stop'] == 0){
                            if($team_amount>=$one['amount'] && $v['zhituinums']>=2){
                                $userModel->where(['id'=>$v['id']])->update(['level'=>1]);
                            }elseif ($team_amount>=$two['amount'] && $v['zhituinums']>=3){
                                $userModel->where(['id'=>$v['id']])->update(['level'=>2]);
                            }elseif ($team_amount>=$three['amount'] && $v['zhituinums']>=3){
                                $lwhere['level']=['>=',2];
                                $num  = $userModel->where($lwhere)->where("FIND_IN_SET(?, pids)", [$v['id']])->count();
                                if($num>=3){
                                    $userModel->where(['id'=>$v['id']])->update(['level'=>3]);
                                }
                            }elseif ($team_amount>=$four['amount'] && $v['zhituinums']>=3){
                                $lwhere['level']=['>=',3];
                                $num  = $userModel->where($lwhere)->where("FIND_IN_SET(?, pids)", [$v['id']])->count();
                                if($num>=3){
                                    $userModel->where(['id'=>$v['id']])->update(['level'=>4]);
                                }
                            }elseif ($team_amount>=$five['amount'] && $v['zhituinums']>=3){
                                $lwhere['level']=['>=',4];
                                $num  = $userModel->where($lwhere)->where("FIND_IN_SET(?, pids)", [$v['id']])->count();
                                if($num>=3){
                                    $userModel->where(['id'=>$v['id']])->update(['level'=>5]);
                                }
                            }elseif ($team_amount>=$six['amount'] && $v['zhituinums']>=3){
                                $lwhere['level']=['>=',5];
                                $num  = $userModel->where($lwhere)->where("FIND_IN_SET(?, pids)", [$v['id']])->count();
                                if($num>=3){
                                    $userModel->where(['id'=>$v['id']])->update(['level'=>6]);
                                }
                            }else{

                            }
                        }
                    }
                }
                Db::commit();
                $this->success('校正成功1');
            }catch(Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            $this->success('校正成功');
        }
    }

}
